// src/components/Message/Message.js
import { createApp, reactive, h } from "vue";
import MessageComponent from "./Message.vue";

const state = reactive({ messages: [] });
let idCounter = 0;

function addMessage(content, type = "info", duration = 3000) {
  const id = idCounter++;
  const message = {
    id,
    content,
    type,
    duration,
    timeoutId: null,
  };

  state.messages.push(message);

  startTimer(message, duration);

  return id;
}

function startTimer(message, duration) {
  if (message.timeoutId) clearTimeout(message.timeoutId);
  message.timeoutId = setTimeout(() => removeMessage(message.id), duration);
}

function removeMessage(id) {
  const index = state.messages.findIndex(m => m.id === id);
  if (index !== -1) state.messages.splice(index, 1);
}

const Message = {
  success: (msg, duration) => addMessage(msg, "success", duration),
  warn: (msg, duration) => addMessage(msg, "warn", duration),
  error: (msg, duration) => addMessage(msg, "error", duration),
  info: (msg, duration) => addMessage(msg, "info", duration),
};

const container = document.createElement("div");
document.body.appendChild(container);

createApp({
  render: () => h(MessageComponent, { messages: state.messages }),
}).mount(container);

export default Message;

export { state, startTimer, removeMessage };
